<template>
  <div
    class="screenShots"
    ref="screenShotsRefs"
  >
    <img
      class="screenShots-img"
      id="screenShotsBoxLow"
      :src="this.imgSrc"
      draggable="false"
      @dragstart="noneFun($event)"
    >

    <div
      class="screenShots-box"
      @mousedown="boxDownFun($event)"
      @mousemove="boxMoveFun($event)"
      @mouseup="boxUpFun($event)"
      :style="{ borderWidth: `${(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)?0:(identifyVisible?0:5)}px` }"
    >

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-span text-noSelect"
        :style="{top:`${this.maskTop-30>10?this.maskTop-30:this.maskTop-5}px`,left:`${this.maskLeft+3}px`,}"
      >
      {{this.maskWidth}} x {{this.maskHeight}}
      </div>

      <!-- 阴影 start -->
      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-top screenShots-mask"
        :style="{top:'0px', left:'0px', width:'100%', height:`${this.maskTop}px`}"
      ></div>

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-left screenShots-mask"
        :style="{top:`${this.maskTop}px`, left:'0px', width:`${this.maskLeft}px`, height:`${this.maskHeight}px`}"
      ></div>
      <!-- 阴影 end -->

      <!-- 截图选中区域 start -->
      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-topLeft"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop-7}px`, left:`${this.maskLeft-7}px`, cursor:'nw-resize',
        border: `2px solid`,
        }"
        @mousedown="borderDown($event, 'topLeft')"
      >
      </div>

      <div
        v-show="( (this.maskWidth-4)>0&&this.maskHeight>0&&this.boxWidth>0&&this.boxHeight>0)"
        class="screenShots-box-center-top"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop-5}px`, left:`${this.maskLeft+2}px`, width:`${this.maskWidth-4}px`, height:`${5}px`, cursor:'n-resize',
        borderBottom: `3px solid`,
        }"
        @mousedown="borderDown($event, 'top')"
      >
      </div>

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-topRight"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop-7}px`, left:`${this.maskLeft+this.maskWidth-2}px`, cursor:'sw-resize',
        border: `2px solid`,
        }"
        @mousedown="borderDown($event, 'topRight')"
      >
      </div>

      <div
        v-show="(this.maskWidth>0&&(this.maskHeight-4)>0&&this.boxWidth>0&&this.boxHeight>0)"
        class="screenShots-box-center-left"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop+2}px`, left:`${this.maskLeft-5}px`, width:`${5}px`, height:`${this.maskHeight-4}px`, cursor:'w-resize',
        borderRight: `3px solid`, }"
        @mousedown="borderDown($event, 'left')"
      >
      </div>

      <!-- 移动的 -->
      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center text-noSelect"
        :style="{top:`${this.maskTop}px`,left:`${this.maskLeft}px`,width:`${this.maskWidth}px`,height:`${this.maskHeight}px`,}"
        id="screenShotsBox"
        @mousedown="borderDown($event, 'center')"
        @dragstart="noneFun($event)"
      >
      </div>

      <!-- 底层截图的 -->
      <!-- <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-low text-noSelect"
        :style="{top:`${this.maskTop}px`,left:`${this.maskLeft}px`,width:`${this.maskWidth}px`,height:`${this.maskHeight}px`,
          background: `url(${this.imgSrc}) no-repeat ${-this.maskLeft}px ${-this.maskTop}px`,}"
        id="screenShotsBoxLowOld"
      >
      </div> -->

      <div
        v-show="(this.maskWidth>0&&(this.maskHeight-4)>0&&this.boxWidth>0&&this.boxHeight>0)"
        class="screenShots-box-center-right"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop+2}px`, left:`${this.maskLeft+this.maskWidth}px`, width:`${5}px`, height:`${this.maskHeight-4}px`, cursor:'w-resize',
        borderLeft: `3px solid`, }"
        @mousedown="borderDown($event, 'right')"
      >
      </div>

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-bottomLeft"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop+this.maskHeight-2}px`, left:`${this.maskLeft-7}px`, cursor:'sw-resize',
        border: `2px solid`,
        }"
        @mousedown="borderDown($event, 'bottomLeft')"
      >
      </div>

      <div
        v-show="( (this.maskWidth-4)>0&&this.maskHeight>0&&this.boxWidth>0&&this.boxHeight>0)"
        class="screenShots-box-center-bottom"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop+this.maskHeight}px`, left:`${this.maskLeft+2}px`, width:`${this.maskWidth-4}px`, height:`${5}px`, cursor:'n-resize',
        borderTop: `3px solid`, }"
        @mousedown="borderDown($event, 'bottom')"
      >
      </div>

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-center-bottomRight"
        :class="{'borderColor':(this.maskWidth!=0&&this.maskHeight!=0)}"
        :style="{top:`${this.maskTop+this.maskHeight-2}px`, left:`${this.maskLeft+this.maskWidth-2}px`, cursor:'nw-resize',
        border: `2px solid`,
        }"
        @mousedown="borderDown($event, 'bottomRight')"
      >
      </div>
      <!-- 截图选中区域 end -->

      <!-- 阴影 start -->
      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-right screenShots-mask"
        :style="{top:`${this.maskTop}px`,left:`${this.maskLeft+this.maskWidth}px`,width:`${this.boxWidth-(this.maskLeft+this.maskWidth)}px`,height:`${this.maskHeight}px`}"
      ></div>

      <div
        v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
        class="screenShots-box-bottom screenShots-mask"
        :style="{top:`${this.maskTop+this.maskHeight}px`,left:'0px',width:'100%',height:`${this.boxHeight-(this.maskTop+this.maskHeight)}px`}"
      ></div>
      <!-- 阴影 end -->

    </div>

    <!-- 放大镜效果 start -->
    <div
      v-show="(this.boxWidth&&this.boxHeight&&ampVisible&&this.maskWidth==0&&this.maskHeight==0)"
      class="screenShots-amp text-noSelect"
      :style="{top:`${( (this.mouse.top + 160 >=(this.boxHeight))?(this.mouse.top - 150):
              (
                this.mouse.top + 20
              )
          )}px`,
          left: `${( (this.mouse.left + 134 >=(this.boxWidth))?(this.mouse.left - 134):
              (
                this.mouse.left + 20
              )
          )}px`,}"
    >
      <div
        class="screenShots-amp-imgDiv"
      >
        <div class="screenShots-amp-imgDiv-xLine">
        </div>

        <div class="screenShots-amp-imgDiv-yLine">
        </div>

        <img
          class="screenShots-amp-img"
          :src="this.imgSrc"
          draggable="false"
          @dragstart="noneFun($event)"
          :style="{margin: `-${(this.mouse.top-25)>0?(this.mouse.top-25):0}px 0 0 -${(this.mouse.left-25)>0?(this.mouse.left-25):0}px`}"
        />
      </div>

      <div
        class="screenShots-amp-imgInfo"
      >
        P：({{this.mouse.top}}，{{this.mouse.left}})
      </div>
    </div>
    <!-- 放大镜效果 end -->

    <!-- 操作按钮 start -->
    <div
      v-show="(this.maskWidth&&this.maskHeight&&this.boxWidth&&this.boxHeight)"
      class="screenShots-btn text-noSelect"
      :style="{top:`${( (this.maskHeight>=(this.boxHeight-100))?(this.maskTop+10):
              (
                (this.maskTop+this.maskHeight+10+40)>=this.boxHeight?(this.maskTop-50):
                (this.maskTop+this.maskHeight+10)
              )
          )}px`,
          left: `${((this.maskLeft+this.maskWidth-225)<=10?10:(
              (this.maskLeft+this.maskWidth)>=this.boxWidth-10?(this.boxWidth-10-225):
              (this.maskLeft+this.maskWidth-225)
            )
          )}px`,}"
    >
      <div
        class="screenShots-btn-sys"
        @click="!screenShotsBtn?imgDownload(true):noneFun"
        :style="{color:`${screenShotsBtn?'#333':null}`,}"
      >
        <vi-icon type="check-square-o"></vi-icon>
        同步至列表
      </div>

      <div class="screenShots-btn-line">
      </div>

      <div
        class="screenShots-btn-cancel"
        @click="!screenShotsBtn?btnCancel(true, false):noneFun"
        :style="{color:`${screenShotsBtn?'#333':null}`,}"
      >
        <vi-icon type="close-square-o"></vi-icon>
        取消
      </div>

      <div
        class="screenShots-btn-look"
        @click="!screenShotsBtn?imgDownload(false):noneFun"
        :style="{color:`${screenShotsBtn?'#333':null}`,}"
      >
        <vi-icon type="profile"></vi-icon>
        查看
      </div>

    </div>
    <!-- 操作按钮 end -->

    <!-- 识别弹窗 start -->
    <vi-modal
      title="识别结果"
      v-if="identifyVisible"
      width="800px"
      :destroyOnClose="true"
      :maskClosable="false"
      :visible="identifyVisible"
      okText="复制全部"
      class="identify-modal"
      @ok="handleOk($event)"
      @cancel="handleCancel"
    >
      <status
        v-show="identifyResultStatus == 0"
        class="status"
      />

      <div
        v-show="identifyResultStatus == 1"
        class="modal-identifyResult text-noSelect"
        style="color: #999; textAlign: center;"
      >
          暂无识别内容
      </div>

      <!-- 拖动文件选中文本组件 -->
      <!-- <selection
        :keyId="'screenShots'"
        :copyCallback="handleCancel"
      > -->

      <div v-show="identifyResultStatus == 2"  class="modal-identifyResult">
          {{identifyResult}}
      </div>

      <!-- </selection> -->

      <textarea v-show="identifyResultStatus == 2" class="modal-identifyResult-hidden" id="screen-identifyResult">{{identifyResult}}</textarea>

      <textarea v-show="identifyResultStatus == 2" class="modal-identifyResult-hidden" id="screen-identifyResult-copy"></textarea>

    </vi-modal>
    <!-- 识别弹窗 end -->

  </div>
</template>

<script>
  import html2canvas from 'html2canvas';
  import axios from 'axios';
  import activeShowMixin from "../../mixin/activeShow.mixin";
  import status from "../public/status";
  import selection from "../public/selection";
  import $ from 'jquery';

  import { baseURL } from "../../libs/http.js";

  import src from "../../assets/image/no-file.png";

export default {
  name: "screenShots",
  components: { status, selection },
  mixins: [activeShowMixin],
  mounted() {
    console.log('screenShots mounted',);
    this.screenMounted();
    this.boxRefs();

    // 解决页面全选持续问题
    if(window.getSelection() && this.$refs.screenShotsRefs && !this.identifyVisible ){
        this.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
        var range = window.getSelection();//创建range
        range.selectAllChildren(this.$refs.screenShotsRefs);//range 选择obj下所有子内容
        range.selectAllChildren(this.$refs.screenShotsRefs) && range.collapseToEnd();
    }

  },
  beforeUpdate() {
    this.boxRefs();

    // console.log( 'screenShots beforeUpdate', this.identifyVisible, );
    // 有弹窗 是截图状态
    if(this.identifyVisible && this.imgSrc && $(".ant-modal-wrap") && window.getSelection().toString() == '' ){

      // 生成默认按钮
      let that = this;
      let copyText = ''; // 记录拖动动作结束
      let oldCopyText = ''; // 记录比较是否重复拖动
      let domPos = { x: 0, y: 0, w: 60, h: 32, }; // 按钮的大小和位置，做点击判断的
      let dom = "<div class='modal-selection-btn'><i class='icon iconfont icon-file-copy modal-selection-btn-icon'></i>复制</div>";
      $(".modal-selection-btn").remove();
      $(".ant-modal-wrap").prepend(dom);
      $(".modal-selection-btn").css("display", "none");

      $(".modal-selection-btn").on('click', function(event) {
        console.log('modal-selection-btn click', event);
        event.stopPropagation();

        let dom = document.getElementById("screen-identifyResult-copy");
        dom.select(); // 选择对象
        document.execCommand("Copy");

        if(document.execCommand("Copy")){
          that.$message.success(`文字复制成功！`);
        }else{
          that.$message.warning(`文字复制失败！`);
        }
        // that.identifyVisible = false;
        that.btnCancel(true, false);
      });

      let ctryA = false;
      $(document).keydown(function(event){
          // event.keyCode 65 a键
          if (event.ctrlKey && event.keyCode == 65){
            ctryA = true;
            $(".modal-selection-btn").css("display", "none");
            // console.log('keydown', event.ctrlKey, event.keyCode, that.btnStatus );
          }
      });

      // let events = { clientX : 0, clientY : 0,  }; // 鼠标落点记录
      // let copyDom = "<p><p>";
      $(".ant-modal-wrap").on('click', function(event) {
          event.stopPropagation();

          // 组织重复点击，但是并没有用
          // if(event.clientX == events.clientX && event.clientY == events.clientY ){
          //   return
          // }
          // 重复点击判断
          // events = { clientX : event.clientX+0, clientY : event.clientY+0};

          // 判断是否点击了按钮
          if( event.clientX > domPos.x-2 && event.clientX < domPos.x+domPos.w+2 && event.clientY > domPos.y-2 && event.clientY < domPos.y+domPos.h+2 && false ){
            let dom = document.getElementById("screen-identifyResult-copy");
            dom.select(); // 选择对象
            document.execCommand("Copy");

            if(document.execCommand("Copy")){
              that.$message.success(`文字复制成功！`);
            }else{
              that.$message.warning(`文字复制失败！`);
            }
            that.identifyVisible = false;
            that.btnCancel(true, false);
            return
          }

          console.log('ant-modal-wrap click', event);
          // 复制
          if( window.getSelection().toString() !== '' ){
            // 重复选择结果，但是鼠标位置变了，取消选择
            if( window.getSelection().toString() == oldCopyText){

              that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
              var range = window.getSelection();//创建range
              range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
              range.collapseToEnd();

              $(".modal-selection-btn").css("display", "none");

              copyText = '';
              oldCopyText = '';
              // copyDom = "<p><p>";
            }
            else if(window.getSelection().toString() !== oldCopyText && that.identifyVisible && that.imgSrc!=='' ){
              $(".modal-selection-btn").css("display", "block");
              oldCopyText = window.getSelection().toString();
              $("#screen-identifyResult-copy").text(window.getSelection().toString());

            }
          }
          else{
            $(".modal-selection-btn").css("display", "none");
          }

      });

      let mouseOnce = { x: 0, y: 0, }; // 点击的初始位置，拖动出探测之后使用。

      $(".ant-modal-wrap").on('mousedown', function(event) {
          // console.log('ant-modal-wrap mousedown', event, window.getSelection().toString(), $(".modal-selection-btn") );
          mouseOnce = { x: 0, y: 0, };

          if( event.clientX >= domPos.x && event.clientX <= domPos.x+60 && event.clientY >= domPos.y && event.clientY <= domPos.y+32 ){
            // 落点范围正确
          }
          else if(event.button == 2 && window.getSelection().toString() !== '' ){
            // 落点范围正确
          }
          else {
            $(".modal-selection-btn").css("display", "none");
          }

          if(ctryA){
            ctryA = false;
            copyText = '';
            oldCopyText = '';
            domPos = { x: 0, y: 0, w: 60, h: 32, };
            $(".modal-selection-btn").css("display", "none");
            that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
            var range = window.getSelection();//创建range
            range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
            range.collapseToEnd();
          }

          return
          // $(".modal-selection-btn").css("display", "none");
          // that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
          // var range = window.getSelection();//创建range
          // range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
          // range.collapseToEnd();

          if(event.button == 0 || event.button == 1 ){
            // 初始所有信息
            copyText = '';
            oldCopyText = '';
            domPos = { x: 0, y: 0, w: 60, h: 32, };
            $(".modal-selection-btn").css("display", "none");
            that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
            var range = window.getSelection();//创建range
            range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
            range.collapseToEnd();
          }
          else if(event.button == 2){
            // console.log('ant-modal-wrap mousedown', event, window.getSelection().toString(), );
          }
          //

      });

      $(".ant-modal-wrap").on('mouseup', function(event) {
          // console.log('ant-modal-wrap mousedown', event, window.getSelection().toString(), $(".identify-modal"), $(".ant-modal-content") );

          if(event.button == 2 && window.getSelection().toString() == '' ){
            // console.log('ant-modal-wrap mouseup', event, window.getSelection().toString(), );
            copyText = '';
            oldCopyText = '';
            domPos = { x: 0, y: 0, w: 60, h: 32, };
            $(".modal-selection-btn").css("display", "none");
            that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
            var range = window.getSelection();//创建range
            range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
            range.collapseToEnd();
            return
          }

          if( (event.button == 0 || event.button == 1) && window.getSelection().toString() == '' ){
            // 初始所有信息
            copyText = '';
            oldCopyText = '';
            domPos = { x: 0, y: 0, w: 60, h: 32, };
            $(".modal-selection-btn").css("display", "none");
            that.$refs.screenShotsRefs.focus() //解决ff不获取焦点无法定位问题
            var range = window.getSelection();//创建range
            range.selectAllChildren(that.$refs.screenShotsRefs);//range 选择obj下所有子内容
            range.collapseToEnd();
          }

      });

      $(".ant-modal-wrap").on('mousemove', function(event) {

          if( window.getSelection().toString() !== '' && mouseOnce.x == 0 && mouseOnce.y == 0 ){
            mouseOnce = { x: event.clientX, y: event.clientY }
          }

          if( window.getSelection().toString() !== copyText && window.getSelection().toString() !== '' ){
            // $(".modal-selection-btn").css("display", "none");
            let y = event.clientY+10;
            let x = event.clientX+5;
            if( y > $(".identify-modal")[0].offsetTop + 50 &&
                y < $(".identify-modal")[0].offsetTop + $(".identify-modal")[0].clientHeight - 80 &&
                x > $(".identify-modal")[0].offsetLeft &&
                x < $(".identify-modal")[0].offsetLeft + $(".identify-modal")[0].clientWidth
              ){
              // 正常
            }
            else{
              // 不正常，使用初始位置
              y = mouseOnce.y+20
              x = mouseOnce.x+5
            }

            $(".modal-selection-btn").css("top", y );
            $(".modal-selection-btn").css("left", x );
            domPos = { x: x, y: y, w: 60, h: 32, };
            copyText = window.getSelection().toString();
          }
      });

    }
  },
  destroyed(){
    // console.log('screenShots destroyed', $(".modal-selection-btn"), this.identifyVisible );
    $(".modal-selection-btn").css("display", "none");
  },
  data() {
      return {
        boxWidth: 1920, // 截图区域
        boxHeight: 1080, // 截图区域
        maskWidth: 0, // 遮罩区域
        maskHeight: 0, // 遮罩区域
        maskTop: 0, // 遮罩区域
        maskLeft: 0, // 遮罩区域
        screenShotsStatus: '', // none没框选 center有框选，移动 其他个角度
        screenShotsTop: 0, // 落脚点
        screenShotsLeft: 0, // 落脚点
        oldTop: 0, // 移动前
        oldLeft: 0, // 移动前
        oldWidth: 0, // 移动前
        oldHeight: 0, // 移动前
        identifyVisible: false, // 识别弹窗
        identifyResult: '', // 识别结果
        identifyResultStatus: 0, // 0加载状态 1无内容 2正常结果
        ampVisible: false, // 放大镜展示隐藏
        mouse: {top: 0, left: 0}, // 当前鼠标位置
        screenShotsBtn: false, // 按钮区域是否点击了（点击之后不能重复点击）
      }
  },
  watch: {
    screenKeyStatus(newValue) {
      if(newValue === 2 ){
        this.setScreenKeyStatus(0); // 修改状态
        this.screenMounted(); // 遮罩层关闭
        this.btnCancel(true, false);
      }
    }
  },
  methods:{
    // refs 查询
    boxRefs(){
      // console.log(this.$refs);
      if(this.boxWidth !== this.$refs.screenShotsRefs.clientWidth ){
        this.boxWidth = this.$refs.screenShotsRefs.clientWidth;
      }

      if(this.boxHeight !== this.$refs.screenShotsRefs.clientHeight){
        this.boxHeight = this.$refs.screenShotsRefs.clientHeight;
      }
    },
    // 图片下载
    imgDownload(status) {
      // console.log( 'imgDownload', status );
      this.screenShotsBtn = true;

      if(status){
        // 同步列表
        this.$message.loading(`正在${status?"同步":"识别"}..`, 0);
      }
      else{
        // 识别截图
        this.identifyVisible = true;
        this.identifyResultStatus = 0;
        this.moveDialog();
        // 清理上传识别数据
        this.identifyResult = '';
      }

      setTimeout(() => {
      // 先弹窗，再识别
        let option = {
            logging: false,
            scale: 1,
            width: this.maskWidth,
            height: this.maskHeight,
            x: this.maskLeft,
            y: this.maskTop,
        };

        if(!status){
          this.maskWidth = 0;
          this.maskHeight = 0;
          this.maskTop = 0;
          this.maskLeft = 0;
          this.screenShotsStatus = ''; // none没框选 center有框选，移动 其他个角度
          this.screenShotsTop = 0; // 落脚点
          this.screenShotsLeft = 0; // 落脚点
          this.oldTop = 0; // 移动前
          this.oldLeft = 0; // 移动前
          this.oldWidth = 0; // 移动前
          this.oldHeight = 0; // 移动前
          this.mouse = {top: 0, left: 0}; // 当前鼠标位置
          this.ampVisible = false; // 放大镜关闭
        }

      html2canvas(document.getElementById('screenShotsBoxLow'), option ).then(canvas => {
          this.imgmap = canvas.toDataURL();
          // var bstr = atob(this.imgmap.split(',')[1])
          // var n = bstr.length
          // var u8arr = new Uint8Array(n)
          // while (n--) {
          //     u8arr[n] = bstr.charCodeAt(n)
          // }
          // var blob = new Blob([u8arr])
          // let fd = new FormData()
          // fd.append('files', blob);

          try {
            axios({
                method: 'post',
                url: this.uploadUrl,
                withCredentials: true,
                data: {"imageBase64": this.imgmap, "saveImage": status},
            })
            .then(result => {
              // console.log(this.imgmap, canvas.toDataURL(), );
              this.$message.destroy();
              if(this.identifyVisible)
              if(result.status === 200){
                if(result.data.state.ok === 1){

                  if(status){
                    this.$message.success(`截图${status?'同步列表':"识别"}成功！`);
                  }
                  else if(!status && result.data.body !== '' ){
                    this.identifyResult = result.data.body;
                    this.identifyResultStatus = 2;
                    this.$message.success(`截图${status?'同步列表':"识别"}成功！`);
                  }
                  else if(!status && result.data.body == '' ){
                    this.identifyResultStatus = 1;
                    // this.$message.warning(`截图${status?'同步列表失败':"识别无有效内容"}！`);
                  }

                }
                else{
                  this.identifyResultStatus = 1;
                  if(status){
                    this.$message.warning(`截图${status?'同步列表失败':"识别无有效内容"}！`);
                  }

                }
              }
              else{
                this.identifyResultStatus = 1;
                if(status){
                  this.$message.warning(`截图${status?'同步列表失败':"识别无有效内容"}！`);
                }
              }

              if(status){
                // 同步列表结束
                this.btnCancel(true, true);
              }

            });
          } catch (error) {
            // console.log(error);
          }

      });

      }, 100);


    },
    // 当前鼠标位置
    getMouseFun(event){
      let mouse = {
          top: event.clientY||0,
          left: event.clientX||0,
      }
      this.mouse = mouse;
      // console.log(mouse);
      return mouse;
    },
    // 盒子 落下
    boxDownFun(event) {
      // console.log('落下盒子0', event, this.maskWidth, this.maskHeight );

      if(event.button === 2){
        this.btnCancel(true, false);
      }

      if(!this.maskWidth && !this.maskHeight && event.button === 0 ){
        let mouse = this.getMouseFun(event);
        this.screenShotsStatus = 'none';
        this.screenShotsTop = mouse.top;
        this.screenShotsLeft = mouse.left;

        this.maskTop = mouse.top||0;
        this.maskLeft = mouse.left||0;
        this.maskWidth = 1;
        this.maskHeight = 1;
      }
    },
    // 盒子 滑动
    boxMoveFun(event) {
      // console.log('滑动0', event);
      let mouse = this.getMouseFun(event);

      // 放大镜展示
      if(!this.ampVisible){
        this.ampVisible = true;
      }

      switch(this.screenShotsStatus) {
        case 'none':
          // 框选
          // 向右下移动
          if(mouse.top > this.screenShotsTop && mouse.left > this.screenShotsLeft){
            this.maskWidth = mouse.left - this.screenShotsLeft;
            this.maskHeight = mouse.top - this.screenShotsTop;
          }
          // 向右上移动
          else if(mouse.top < this.screenShotsTop && mouse.left > this.screenShotsLeft){
            this.maskTop = mouse.top;
            this.maskWidth = mouse.left - this.screenShotsLeft;
            this.maskHeight = this.screenShotsTop - mouse.top;
          }
          // 向左下移动
          else if(mouse.top > this.screenShotsTop && mouse.left < this.screenShotsLeft){
            this.maskLeft = mouse.left;
            this.maskWidth = this.screenShotsLeft - mouse.left;
            this.maskHeight = mouse.top - this.screenShotsTop;
          }
          // 向左上移动
          else if(mouse.top < this.screenShotsTop && mouse.left < this.screenShotsLeft){
            this.maskTop = mouse.top;
            this.maskLeft = mouse.left;
            this.maskWidth = this.screenShotsLeft - mouse.left;
            this.maskHeight = this.screenShotsTop - mouse.top;
          }
          break;
        case 'center':
          // 移动框选区域
          // 向右下移动
          if(mouse.top > this.screenShotsTop && mouse.left > this.screenShotsLeft){
            this.bumpBox('top', (this.oldTop + (mouse.top - this.screenShotsTop)) );
            this.bumpBox('left', (this.oldLeft + (mouse.left - this.screenShotsLeft)) );
          }
          // 向右上移动
          else if(mouse.top < this.screenShotsTop && mouse.left > this.screenShotsLeft){
            this.bumpBox('top', (this.oldTop - (this.screenShotsTop - mouse.top)) );
            this.bumpBox('left', (this.oldLeft + (mouse.left - this.screenShotsLeft)) );
          }
          // 向左下移动
          else if(mouse.top > this.screenShotsTop && mouse.left < this.screenShotsLeft){
            this.bumpBox('top', (this.oldTop + (mouse.top - this.screenShotsTop)) );
            this.bumpBox('left', (this.oldLeft - (this.screenShotsLeft - mouse.left)) );
          }
          // 向左上移动
          else if(mouse.top < this.screenShotsTop && mouse.left < this.screenShotsLeft){
            this.bumpBox('top', (this.oldTop - (this.screenShotsTop - mouse.top)) );
            this.bumpBox('left', (this.oldLeft - (this.screenShotsLeft - mouse.left)) );
          }
          break;
        case 'topLeft':
          this.changeAngleBox(mouse, {top: (this.oldTop + this.oldHeight) , left: (this.oldLeft + this.oldWidth)});
          break;
        case 'topRight':
          this.changeAngleBox(mouse, {top: (this.oldTop + this.oldHeight) , left: (this.oldLeft)});
          break;
        case 'bottomRight':
          this.changeAngleBox(mouse, {top: (this.oldTop) , left: (this.oldLeft)});
          break;
        case 'bottomLeft':
          this.changeAngleBox(mouse, {top: (this.oldTop) , left: (this.oldLeft + this.oldWidth)});
          break;
        case 'top':
          this.changeRoundBox( 'vertical', mouse, {top: (this.oldTop + this.oldHeight) , left: (this.oldLeft + this.oldWidth)});
          break;
        case 'bottom':
          this.changeRoundBox( 'vertical', mouse, {top: (this.oldTop) , left: (this.oldLeft)});
          break;
        case 'left':
          this.changeRoundBox( 'cross', mouse, {top: (this.oldTop + this.oldHeight) , left: (this.oldLeft + this.oldWidth)});
          break;
        case 'right':
          this.changeRoundBox( 'cross', mouse, {top: (this.oldTop) , left: (this.oldLeft)});
          break;
        default:
          return;
      };
    },
    // 盒子 抬起
    boxUpFun(event) {
      // console.log('抬起', event);
      let mouse = this.getMouseFun(event);
      this.screenShotsStatus = '';
      this.screenShotsTop = mouse.top;
      this.screenShotsLeft = mouse.left;
      this.oldTop = this.maskTop;
      this.oldLeft = this.maskLeft;
    },
    // border 落下
    borderDown(event, type){
      // console.log('落下边框', event, type);
      event.stopPropagation();
      let mouse = this.getMouseFun(event);
      this.screenShotsStatus = type;
      this.screenShotsTop = mouse.top;
      this.screenShotsLeft = mouse.left;
      this.oldTop = this.maskTop;
      this.oldLeft = this.maskLeft;
      this.oldWidth = this.maskWidth;
      this.oldHeight = this.maskHeight;
    },
    // 撞到边框固定
    bumpBox(type, num){
      if(type == 'top' && num <= 0){
        this.maskTop = 0;
      }
      else if(type == 'top' && (num + this.maskHeight) >= this.boxHeight){
        this.maskTop = this.boxHeight - this.maskHeight;
      }
      else if(type == 'left' && num <= 0){
        this.maskLeft = 0;
      }
      else if(type == 'left' && (num + this.maskWidth) >= this.boxWidth){
        this.maskLeft = this.boxWidth - this.maskWidth;
      }
      else {
        type=='top' ? (this.maskTop = num) : (this.maskLeft = num);
      }
    },
    // 夹角框选改变
    changeAngleBox(neww, old){
      this.maskTop = (neww.top<old.top&&neww.left<old.left)?neww.top:
      (
        (neww.top<old.top&&neww.left>old.left)?neww.top:
        (
          (neww.top>old.top&&neww.left>old.left)?old.top:
          (
            (neww.top>old.top&&neww.left<old.left)?old.top:0
          )
        )
      );
      this.maskLeft = (neww.top<old.top&&neww.left<old.left)?neww.left:
      (
        (neww.top<old.top&&neww.left>old.left)?old.left:
        (
          (neww.top>old.top&&neww.left>old.left)?old.left:
          (
            (neww.top>old.top&&neww.left<old.left)?neww.left:0
          )
        )
      );
      this.maskWidth = (neww.top<old.top&&neww.left<old.left)?(old.left-neww.left):
      (
        (neww.top<old.top&&neww.left>old.left)?(neww.left-old.left):
        (
          (neww.top>old.top&&neww.left>old.left)?(neww.left-old.left):
          (
            (neww.top>old.top&&neww.left<old.left)?(old.left-neww.left):0
          )
        )
      );
      this.maskHeight = (neww.top<old.top&&neww.left<old.left)?(old.top-neww.top):
      (
        (neww.top<old.top&&neww.left>old.left)?(old.top-neww.top):
        (
          (neww.top>old.top&&neww.left>old.left)?(neww.top-old.top):
          (
            (neww.top>old.top&&neww.left<old.left)?(neww.top-old.top):0
          )
        )
      );
    },
    // 上下框选改变
    changeRoundBox(type, neww, old){
      switch(type){
        case 'vertical':
          this.maskTop = neww.top<old.top?neww.top:old.top;
          this.maskHeight = neww.top<old.top?old.top-neww.top:neww.top-old.top;
          break;
        case 'cross':
          this.maskLeft = neww.left<old.left?neww.left:old.left;
          this.maskWidth = neww.left<old.left?old.left-neww.left:neww.left-old.left;
          break;
        default:
          return;
      };
    },
    // 空白函数
    noneFun(event){
      event.stopPropagation();
      return false;
    },
    // 取消 status0：是否退出截图 status1：是否刷新列表
    btnCancel(status0, status1){
      let pay = {
          code: 2,
          cmd: "Screenshot_over",
        };

      this.$webSC.webSCAsync(pay).then(res =>{
        // console.log( 'screenOver', res, (res) );
        if(res)
        if(res.cmd == "Screenshot_over" && res.status == 200 ){
          this.screenMounted();

          this.setScreenShotsStatus(false);
          this.setScreenImgSrc('');

          this.screenShotsBtn = false; // 按钮区域是否点击了（点击之后不能重复点击）
          this.identifyVisible = false;
          this.identifyResult = "";
          this.copyResult = "";
          this.identifyResultStatus = 0;

          if(status1){
            // 刷新文件列表树
            this.setNeedRefreshList(true);
          }
        }
      });

      return
      this.maskWidth = 0;
      this.maskHeight = 0;
      this.maskTop = 0;
      this.maskLeft = 0;
      this.screenShotsStatus = ''; // none没框选 center有框选，移动 其他个角度
      this.screenShotsTop = 0; // 落脚点
      this.screenShotsLeft = 0; // 落脚点
      this.oldTop = 0; // 移动前
      this.oldLeft = 0; // 移动前
      this.oldWidth = 0; // 移动前
      this.oldHeight = 0; // 移动前
      this.mouse = {top: 0, left: 0}; // 当前鼠标位置
      this.ampVisible = false; // 放大镜关闭
      this.screenShotsBtn = false;

      if(status0){
        // 结束截图模式
        // this.setScreenShotsStatus(false);
        // this.setScreenImgSrc('');

        this.screenOver();

        // setTimeout(() => {
        //   this.screenMounted();
        // }, 300);
      }

      if(status1){
        // 刷新文件列表树
        this.setNeedRefreshList(true);
      }

    },
    // 弹窗取消
    handleCancel() {
      this.identifyVisible = false;
      this.identifyResult = "";
      this.copyResult = "";
      this.identifyResultStatus = 0;

      setTimeout(() => {
        this.btnCancel(true, false);
      }, 300);
    },
    // 弹窗复制
    handleOk(event) {
      event.stopPropagation();

      if(this.identifyResultStatus == 0){
        return
      }

      if(this.identifyResult !== '' && this.copyResult !== '' ){
        let dom = document.getElementById("screen-identifyResult");
        dom.select(); // 选择对象
        document.execCommand("Copy");

        if(document.execCommand("Copy")){
          this.$message.success(`文字复制成功！`);
        }else{
          this.$message.warning(`文字复制失败！`);
        }

      }
      else{
        // this.$message.warning(`截图识别无有效内容！`);
      }

      // this.identifyVisible = false;
      this.btnCancel(true, false);

    },
    // 截图通信关闭
    screenOver() {
      let pay = {
          code: 2,
          cmd: "Screenshot_over",
        };

      this.$webSC.webSCAsync(pay).then(res =>{
        console.log( 'screenOver', res, (res) );
        if(res)
        if(res.cmd == "Screenshot_over" && res.status == 200 ){
          this.screenMounted();
          this.setScreenShotsStatus(false);
          this.setScreenImgSrc('');
        }
      });
    },
    // 遮罩层隐藏
    screenMounted() {
      let pay = {
          code: 6,
          cmd: "Show_suceess",
        };

      this.$webSC.webSCAsync(pay).then(res =>{ });
    },
    // 移动dialog
    moveDialog() {
      this.$nextTick(() => {
        let dialogHeaderEl = document.querySelector('.ant-modal-header')
        let dialogEl = document.querySelector('.ant-modal')

        dialogHeaderEl.style.cursor = 'move'

        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft
          const disY = e.clientY - dialogHeaderEl.offsetTop

          const screenWidth = document.body.clientWidth // body当前宽度
          const screenHeight = document.body.clientHeight // 可见区域高度(应为body高度，可某些环境下无法获取)

          const dragDomWidth = dialogEl.offsetWidth // 对话框宽度
          const dragDomheight = dialogEl.offsetHeight // 对话框高度

          const minDragDomLeft = dialogEl.offsetLeft
          const maxDragDomLeft = screenWidth - dialogEl.offsetLeft - dragDomWidth

          const minDragDomTop = dialogEl.offsetTop
          const maxDragDomTop = screenHeight - dialogEl.offsetTop - dragDomheight

          // 获取到的值带px 正则匹配替换
          // let styL = getComputedStyle(dialogEl, null).left
          // let styT = getComputedStyle(dialogEl, null).top
          let styL = dialogEl.getBoundingClientRect().left // 兼容低版本移动弹窗效果
          let styT = dialogEl.getBoundingClientRect().top // 兼容低版本移动弹窗效果

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          /*if (styL.includes('%')) {
            styL = +screenWidth * (+styL.replace(/\%/g, '') / 100)
            styT = +screenHeight * (+styT.replace(/\%/g, '') / 100)
          } else {
            styL = +styL.replace(/\px/g, '')
            styT = +styT.replace(/\px/g, '')
          }*/

          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            let left = e.clientX - disX
            let top = e.clientY - disY

            // 边界处理
            if (-(left) > minDragDomLeft) {
              left = -(minDragDomLeft)
            } else if (left > maxDragDomLeft) {
              left = maxDragDomLeft
            }

            if (-(top) > minDragDomTop) {
              top = -(minDragDomTop)
            } else if (top > maxDragDomTop) {
              top = maxDragDomTop
            }

            // 移动当前元素
            dialogEl.style.cssText += `;left:${left + styL}px;top:${top + styT}px;margin:0;`
          }

          document.onmouseup = function (e) {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      })
    },
  },
  computed: {
    dirId() {
      let id = '';
      this.$store.state.file.folderList.map( v =>{
        if(v.dirType === 0){
          id = v.id
        }
      } )
      return id;
    },
    userId() {
      return this.$store.state.user.userId;
    },
    // 上传接口
    uploadUrl() {
      return `${baseURL}${this.$url.screenShots.url}/${this.userId}/${this.dirId}`;
    },
    // 截图地址
    imgSrc() {
      // return src;
      return this.$store.state.file.screenImgSrc;
    },
    // 通信状态
    screenKeyStatus() {
      return this.$store.state.status.screenKeyStatus;
    },
  }
};
</script>

<style lang="less" scoped>
.screenShots{
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
}

.screenShots-img{
  z-index: 1;
  width: 100%;
  // height: 100%;
}

.screenShots-box{
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 2;
  box-sizing: border-box;
  border-style: solid;
  border-color: @primary
}

.screenShots-mask{
  background-color: #666;
  opacity: 0.5;
  position: absolute;
}

.screenShots-box-center{
  cursor: move;
  overflow: hidden;
}

.screenShots-box-center-span{
  position: absolute;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  padding: 0 3px;
  color: #fff;
  z-index: 3;
}

.screenShots-box-center-low{
  position: absolute;
  overflow: hidden;
  z-index: 0;
}

.screenShots-box-center-img{
  // position: absolute;
  overflow: hidden;
}

.screenShots-box-center-top, .screenShots-box-center-right, .screenShots-box-center-left, .screenShots-box-center-bottom, .screenShots-box-center{
  position: absolute;
  z-index: 3;
  box-sizing: border-box;
  &.borderColor{
    border-color: @primary !important;
  }
}

.screenShots-box-center-topLeft, .screenShots-box-center-topRight, .screenShots-box-center-bottomLeft, .screenShots-box-center-bottomRight{
  position: absolute;
  z-index: 3;
  width: 9px;
  height: 9px;
  background-color: #fff;
  border-radius: 50%;
  &.borderColor{
    border-color: @primary !important;
  }
}

.screenShots-amp{
  position: absolute;
  width: 102px;
  height: 130px;
  border: 1px solid @primary;
  border-radius: 2px;
  z-index: 3;
  display: block;
  box-sizing: border-box;
  background-color: #333;
  overflow: hidden;
}

.screenShots-amp-imgDiv{
  width: 50px;
  height: 50px;
  overflow: hidden;
  transform-origin: 0% 0%;
  transform: scale(2);
}

.screenShots-amp-imgDiv-xLine{
  width: 50px;
  height: 1px;
  background-color: @primary;
  position: absolute;
  top: 24.5px;
  z-index: 3;
}

.screenShots-amp-imgDiv-yLine{
  width: 1px;
  height: 50px;
  background-color: @primary;
  position: absolute;
  left: 24.5px;
  z-index: 3;
}

.screenShots-amp-img{
  transform-origin: 0% 0%;
  transform: scale(1);
}

.screenShots-amp-imgInfo{
  width: 100px;
  height: 25px;
  line-height: 25px;
  color: #fff;
  font-size: 12px;
  padding: 0 3px;
  margin-top: 50px;
}

.screenShots-btn{
  position: absolute;
  width: 225px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  background-color: #fff;
  color: #333;
  font-size: 14px;
  z-index: 4;
  display: flex;
}

.screenShots-btn-sys{
  width: 100px;
  text-align: center;
}

.screenShots-btn-line{
  margin: 9px;
  width: 1px;
  background-color: #666;
}

.screenShots-btn-sys, .screenShots-btn-cancel, .screenShots-btn-look{
  &:hover{
    color: @primary;
  }
}

.screenShots-btn-cancel, .screenShots-btn-look{
  width: 52px;
  text-align: center;
}

.text-noSelect{
  -webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}

.modal-identifyResult{
  width: 100%;
  height: 25vh;
  overflow: auto;
  z-index: 1;
}

.modal-identifyResult-hidden{
  width: 0;
  height: 0;
  overflow: hidden;
  border-color: transparent;
  padding: 0px;
  margin: 0px;
  z-index: 0;
  position: absolute;
}

.status {
  z-index: 2;
  width: 100%;
  height: 25vh;
}

</style>

<style lang="less">
.modal-selection-btn{
    position: absolute;
    z-index: 2;
    height: 32px;
    line-height: 32px;
    width: 60px;
    border: 1px solid #dcdcdc;
    border-radius: 3px;
    background-color: #fff;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select: none;
    &:hover{
        color: @primary;
    }
}

.modal-selection-btn-icon{
    font-size: 14px;
    margin: 0 3px 0 0;
}

/*
老版本上传
axios({
    method: 'post',
    url: this.uploadUrl,
    withCredentials: true,
    data: fd,
})
.then(result => {
  // console.log(this.imgmap, fd, this.uploadUrl, blob, result);

  this.setFileLoadingState(false);
  this.$message.destroy();

  if(result.status === 200){
    if(result.data.body){
      this.setNeedRefreshList(true);
      this.$message.success(`${result.data.body}！`);
    }
  }
  else{
    this.$message.success(`文件上传失败！`);
  }
  this.btnCancel();
  this.setScreenShotsStatus(false);

});

下载
if (window.navigator.msSaveOrOpenBlob) {
    var bstr = atob(this.imgmap.split(',')[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, `截图_${new Date().toLocaleString()}` + '.' + 'png')
} else {
    // 这里就按照chrome等新版浏览器来处理
    const a = document.createElement('a')
    a.href = this.imgmap
    a.setAttribute('download', `截图_${new Date().toLocaleString()}.png`)
    a.click()
}
*/
</style>
